<template>
    <view class="widget-video" :style="{ height: videoHeight }">
        <!-- 下拉刷新 -->
        <!-- <view v-if="marginTop>0" class="refresh-box">
			松开刷新
		</view> -->
        <!-- 视频容器 -->
        <view
            class="scroll-video-box"
            @touchstart="touchStart"
            @touchmove="touchMove"
            @touchend="touchEnd"
            :style="{ marginTop: marginTop + 'px', transition: transition }"
        >
            <view
                ref="videoItemBox"
                class="video-item-box"
                v-for="(item, index) in videoList"
                :key="index"
                :style="{ height: videoHeight }"
            >
                <!-- 视频封面，避免黑屏 -->
                <image
                    v-if="
                        (item.recordType === '0' || item.recordType === '8') &&
                        currentIndex !== index
                    "
                    class="video-cover"
                    :src="item.posterUrl || item.videoCover"
                    mode="aspectFill"
                />
                <!-- 只渲染当前视频 -->
                <video
                    v-if="
                        (item.recordType === '0' || item.recordType === '8') &&
                        currentIndex === index
                    "
                    @click="
                        ($event) => {
                            pauseVideo($event, item);
                        }
                    "
                    :id="item.id"
                    class="fullscreen-video"
                    :src="item.videoUrl"
                    @error="videoError(item, index)"
                    @loadedmetadata="loadedmetadata"
                    :poster="item.posterUrl || item.videoCover"
                    :controls="controls"
                    @timeupdate="videoUpdate"
                    @ended="videoEnded"
                    :show-progress="false"
                    :show-fullscreen-btn="false"
                    :show-play-btn="false"
                    :loop="true"
                    :autoplay="false"
                    :show-center-play-btn="false"
                    :object-fit="item.objectFit || 'cover'"
                ></video>
                <view
                    v-if="item.recordType === '1'"
                    style="width: 100%; height: 100%; position: relative"
                    @click="
                        ($event) => {
                            pauseVideo($event, item);
                        }
                    "
                >
                    <image
                        style="width: 100%; height: 100%"
                        :src="item.videoCover"
                        mode="aspectFit"
                    />

                    <!-- <audio :id="item.id" :src="item.videoUrl" :poster="item.videoCover"></audio> -->
                </view>
                <block
                    v-for="(fabulous, fabulousIndx) in fabulousArr"
                    :key="fabulousIndx"
                >
                    <i
                        v-if="fabulous != null"
                        @click="fabulousDbClick"
                        class="iconfont iconxihuan fabulous-item"
                        :style="{
                            top: fabulous.top,
                            left: fabulous.left,
                            opacity: fabulous.opacity,
                            transform: fabulous.transform,
                        }"
                    ></i>
                </block>

                <i
                    :class="[
                        'iconfont iconbofang btn-play',
                        currentStatus == 'pause' && currentIndex == index
                            ? 'show'
                            : '',
                    ]"
                    @click="pauseVideo"
                ></i>
                <view class="video-info">
                    <view class="atavar-box">
                        <!-- <u-image width="100%" height="100%" mode="widthFix" shape="circle" /> -->
                        <image
                            @click="
                                item.recordType === '8'
                                    ? toAdvisor(item.releaseManId)
                                    : ''
                            "
                            width="100%"
                            height="100%"
                            class="atavar-img"
                            shape="circle"
                            :src="
                                item.salesmanAvatar ||
                                'https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/16/7fab9966118946a5904ab3c664b50210.png'
                            "
                        />
                        <!-- <view class="add-follow-btn" @click="followFunc(index,item)">
							<i
								:class="['iconfont inline-block icon-follow', item.isFollow == 1 ? 'iconduihao' : 'iconjia1']"></i>
						</view> -->
                    </view>
                    <view class="icon-box" @click="toggleFabulous(item, index)">
                        <i
                            :class="[
                                'iconfont iconxihuan icon-btn',
                                item.isFabulous == 1 ? 'color-red' : '',
                            ]"
                        ></i>
                        <view class="count-text">{{ item.fabulousCount }}</view>
                    </view>
                    <!-- <view class="icon-box" @click="commontAdd">
                        <i class="iconfont iconIMliaotian-shixin icon-btn"></i>
                        <view class="count-text">{{item.commentCount}}</view>
                    </view> -->
                    <view class="icon-box" style="margin: 20rpx 0">
                        <button
                            open-type="share"
                            style="background: transparent"
                        >
                            <i
                                class="iconfont iconfenxiang icon-btn"
                                style="color: #fff"
                                @click="shareFunc(item)"
                            ></i>
                        </button>

                        <!-- <view class="count-text">{{item.shareCount}}</view> -->
                    </view>
                    <!-- 视频下载 -->
                    <view
                        class="icon-box"
                        style="margin: 20rpx 0"
                        @click="downSaveImage(item)"
                        v-if="
                            item.recordType === '0' || item.recordType === '8'
                        "
                    >
                        <u-icon
                            name="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/12/25/bb35c4de9ae349ac8afbf9b93ff015ea.png"
                            color="#fff"
                            size="32"
                        ></u-icon>
                    </view>
                    <view
                        class="icon-box"
                        v-if="item.goodsId"
                        @click="goToGoodsFunc(item)"
                    >
                        <u-image
                            src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/13/f4119c62b9e945d088d149cf4fcce004.png"
                            width="70rpx"
                            height="70rpx"
                        ></u-image>
                        <!-- <view class="count-text">{{item.shareCount}}</view> -->
                    </view>
                </view>
                <view class="video-title">
                    <!-- 控制条+滑块 -->
                    <view class="slider-container flex_wrap">
                        <view class="currtime">{{ currtime }}</view>
                        <slider
                            class="isSlider"
                            step="1"
                            backgroundColor="#9f9587"
                            activeColor="#d6d2cc"
                            block-color="#FFFFFF"
                            block-size="12"
                            min="0"
                            :max="videoTime"
                            :value="sliderValue"
                        />
                        <view class="currtime">{{ druationTime }}</view>
                    </view>
                    <view class="user-name"
                        >{{ item.userNick ? `${item.userNick}` : "" }}
                    </view>
                    <view class="video-content"
                        ><text>{{
                            item.videoContent ? `${item.videoContent}` : ""
                        }}</text>
                        <text
                            style="
                                padding: 0 10rpx 0 0;
                                font-weight: 400;
                                font-size: 24rpx;
                                color: #588bf3;
                            "
                            v-for="v in tagList(item.tag)"
                            @click="goToBiaoQian(v)"
                            >#{{ v }}</text
                        >
                    </view>
                </view>
            </view>
            <view v-if="videoList.length == 0" class="empty-txt"
                >当前没有可播放视频哦～</view
            >
        </view>

        <!-- 上拉加载 -->
        <!-- <view v-if="videoList.length > 0" class="load-more-box">
			加载更多
		</view> -->
        <!-- 评论弹窗 -->
        <view :class="['commont-box', commontShow ? 'active' : '']">
            <view class="commont-title">{{ currentComment.count }}条评论</view>
            <view class="commont-list">
                <view v-for="(item, index) in currentComment.list" :key="index">
                    <view class="comment-panel">
                        <image
                            class="first-user"
                            :src="item.userHead"
                            mode="widthFix"
                        ></image>
                        <view class="first-comment">
                            <view class="comment-name">{{
                                item.userNick
                            }}</view>
                            <view class="comment-content">{{
                                item.content
                            }}</view>
                            <view class="time-box">
                                <text class="inline-block">{{
                                    item.time
                                }}</text>
                                <view
                                    class="inline-block reply-btn"
                                    @click="reply('first', item, index)"
                                    >回复</view
                                >
                            </view>
                        </view>
                        <view class="fabulous-box">
                            <i
                                :class="[
                                    'iconfont iconxihuan fabulous-btn',
                                    item.isFabulous == '1' ? 'color-red' : '',
                                ]"
                                @click="commentFabulous('first', item, index)"
                            ></i>
                            <view class="fabulous-text">{{
                                item.fabulousCount
                            }}</view>
                        </view>
                    </view>
                    <view style="padding-left: 70rpx">
                        <view
                            class="comment-panel"
                            v-for="(child, childIndex) in item.children"
                            :key="childIndex"
                        >
                            <image
                                class="first-user"
                                :src="child.userHead"
                                mode="widthFix"
                            ></image>
                            <view class="first-comment">
                                <view
                                    class="comment-name"
                                    v-if="child.replyTo == item.userNick"
                                    >{{ child.userNick }}
                                </view>
                                <view class="comment-name" v-else>
                                    <span class="inline-block">{{
                                        child.userNick
                                    }}</span>
                                    <span class="inline-block">
                                        <i
                                            class="iconfont iconxiangyou1"
                                            style="font-size: 8px"
                                        ></i>
                                    </span>
                                    <span class="inline-block">{{
                                        child.replyTo
                                    }}</span>
                                </view>
                                <view class="comment-content">{{
                                    child.content
                                }}</view>
                                <view class="time-box">
                                    <text class="inline-block">{{
                                        child.time
                                    }}</text>
                                    <view
                                        class="inline-block reply-btn"
                                        @click="
                                            reply(
                                                'second',
                                                child,
                                                index,
                                                childIndex
                                            )
                                        "
                                        >回复</view
                                    >
                                </view>
                            </view>
                            <view class="fabulous-box">
                                <i
                                    :class="[
                                        'iconfont iconxihuan fabulous-btn',
                                        child.isFabulous == '1'
                                            ? 'color-red'
                                            : '',
                                    ]"
                                    @click="
                                        commentFabulous(
                                            'second',
                                            child,
                                            index,
                                            childIndex
                                        )
                                    "
                                ></i>
                                <view class="fabulous-text">{{
                                    child.fabulousCount
                                }}</view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 评论输入框 -->
            <input
                class="comment-input"
                @confirm="commentCommit"
                @blur="commentBlur"
                v-model="replyContent"
                :focus="showInput"
                :placeholder="commentPlaceholder"
                type="text"
            />
        </view>
    </view>
</template>

<script>
const currentAudio = uni.createInnerAudioContext();
currentAudio.src =
    "https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/09/b903b9eb625248b49480f582ec3bed46.mp3";
currentAudio.autoplay = false;
currentAudio.loop = true;
// #ifdef APP-NVUE
const dom = weex.requireModule("dom");
// #endif
export default {
    props: {
        // 视频容器高度
        videoHeight: {
            type: String,
            default: "100vh",
        },
        // 列表数据
        data: {
            type: Array,
            default() {
                return [];
            },
        },
        // 当前视频下标
        videoIndex: {
            type: [Number, String],
            default: "0",
        },
        isHide: {
            type: Boolean,
            default: false,
        },
    },
    computed: {
        tagList() {
            return (tag) => {
                return tag
                    ? tag.split(",").filter((ele) => ele && ele !== " ")
                    : [];
            };
        },
    },
    data() {
        // 从props解析视频高度（去除'px'后缀）
        let initialHeight = 0;
        if (this.videoHeight) {
            initialHeight = parseInt(this.videoHeight);
        }
        if (!initialHeight || initialHeight <= 0) {
            initialHeight = uni.getSystemInfoSync().windowHeight || window.innerHeight;
        }
        console.log('初始化视频高度 - props传入:', this.videoHeight, '解析后:', initialHeight);
        
        return {
            // 视频列表数据
            videoList: this.data,
            // 视频实际高度，从props解析，确保整数
            videoRealHeight: Math.round(initialHeight),
            // 双击点赞记录
            fabulousArr: [],
            // 记录点击时间判断单击还是双击，单击暂停，双击点赞
            clickTimer: null,
            // 记录点击时间
            clickTime: 0,
            // 屏幕高度
            windowHeight:
                uni.getSystemInfoSync().windowHeight || window.innerHeight,
            // 动画效果
            transition: "none",
            // 触摸开始值
            startY: 0,
            // 触摸移动值
            moveY: 0,
            // 滑动开始时间
            startTime: 0,
            // 向上滑动距离
            marginTop: 0,
            // 每次向上滑动的距离
            fixMarginTop: 0,
            // 滑动方向
            moveDirection: "",
            // 当前轮播的index
            currentIndex: 0,
            // 当前页的视频对象
            currentVideo: null,
            currentAudio: null,
            // 当前视频的评论
            currentComment: [],
            // 视频状态：播放/暂停
            currentStatus: "play",
            // 是否显示评论
            commontShow: false,
            // 爱心动画双击
            fabulousTime: 0,
            fabulousTimer: null,
            // 显示评论输入框
            showInput: false,

            // 评论提示
            commentPlaceholder: "说点好听的～",
            // 回复对象
            replyType: "video",
            replyObj: {},
            replyIndex: 0,
            replyParentIndex: 0,
            // 评论内容
            replyContent: "",

            videoTime: "", //视频总时长
            sliderValue: 0, //控制进度条slider的值，
            currtime: "00:00", //当前播放时间 -计算后
            druationTime: "00:00", //总时间 -计算后
            controls: true, //是否显示默认播放控件（播放/暂停按钮、播放进度、时间）
        };
    },
    watch: {
        data: {
            handler(n) {
                this.videoList = n;
                // 当数据变化时，重新计算高度
                this.$nextTick(() => {
                    this.recalculateHeight();
                });
            },
            deep: true,
        },
        isHide: {
            handler(n) {
                if (this.videoList[this.currentIndex].recordType === "1") {
                    if (n) {
                        currentAudio.pause();
                        this.currentStatus = "pause";
                    } else {
                        currentAudio.play();
                        this.currentStatus = "play";
                    }
                }
            },
        },
    },
    // #ifdef APP-NVUE
    onReady() {
        dom.getComponentRect(this.$refs.videoItemBox, (option) => {
            if (option && option.size && option.size.height > 0) {
                this.videoRealHeight = option.size.height;
                console.log('APP-NVUE环境视频高度:', this.videoRealHeight);
            }
        });
    },
    // #endif
    mounted() {
        // 立即计算高度，不等待
        this.recalculateHeight();
        
        const timer = setTimeout(() => {
            // 再次计算确保准确
            this.recalculateHeight();
            
            // 初始化第一个视频播放器
            if (
                this.videoList[0].recordType === "0" ||
                this.videoList[0].recordType === "8"
            ) {
                this.currentVideo = uni.createVideoContext(
                    this.videoList[0].id,
                    this
                );
                // 立即播放第一个视频
                this.$nextTick(() => {
                    if (this.currentVideo) {
                        this.currentVideo.play();
                        this.currentStatus = "play";
                    }
                });
            } else {
                currentAudio.play();
            }

            // 初始化评论
            this.currentComment = this.videoList[0].commentObj;
            // 定时清除动画元素
            this.clearFabulousArr();
        }, 500); // 从800ms减少到500ms
    },
    methods: {
        // 重新计算视频高度
        recalculateHeight() {
            //#ifdef APP-NVUE
            // APP-NVUE环境已在onReady中处理
            return;
            //#endif
            
            // 使用DOM查询获取实际容器高度
            const query = uni.createSelectorQuery().in(this);
            query
                .select(".video-item-box")
                .boundingClientRect((data) => {
                    if (data && data.height > 0) {
                        const newHeight = Math.round(data.height);
                        console.log('重新计算高度 - DOM查询:', newHeight, '当前值:', this.videoRealHeight);
                        
                        // 只在高度有明显变化时更新
                        if (Math.abs(newHeight - this.videoRealHeight) > 5) {
                            console.warn('检测到高度变化，从', this.videoRealHeight, '更新为', newHeight);
                            this.videoRealHeight = newHeight;
                            // 高度变化后，重新校准当前视频位置
                            this.marginTop = -this.currentIndex * this.videoRealHeight;
                            this.fixMarginTop = this.marginTop;
                        }
                    } else {
                        console.warn('DOM查询失败，保持当前高度:', this.videoRealHeight);
                    }
                })
                .exec();
        },
        toAdvisor(releaseManId) {
            setTimeout(() => {
                uni.navigateTo({
                    url:
                        "/pages_card/user_card/index?salesmanId=" +
                        releaseManId,
                });
            }, 500);
        },
        loadedmetadata(e) {
            const videoRatio = e.detail.width / e.detail.height;
            if (videoRatio < 1) {
                this.videoList[this.currentIndex].objectFit = "cover";
            } else {
                this.videoList[this.currentIndex].objectFit = "contain";
            }
            let videoTime = e.detail.duration; //视频总时间
            this.videoTime = videoTime;
            this.$forceUpdate();
        },
        // 视频出错
        videoError(item, index) {
            uni.showToast({
                title: "视频出错了!",
                icon: "none",
            });
        },
        // 触摸开始
        touchStart(e) {
            this.transition = "none";
            this.startY = e.touches[0].pageY;
            this.startTime = new Date().getTime();
            
            // 触摸开始时校准位置，确保当前视频完全对齐
            const correctPosition = -this.currentIndex * this.videoRealHeight;
            if (Math.abs(this.marginTop - correctPosition) > 2) {
                console.log(`[touchStart校准] currentIndex:${this.currentIndex}, videoRealHeight:${this.videoRealHeight}`);
                console.log(`[touchStart校准] 当前marginTop:${this.marginTop}, 应该是:${correctPosition}, 偏差:${this.marginTop - correctPosition}px`);
                this.marginTop = correctPosition;
                this.fixMarginTop = correctPosition;
            }
        },

        //播放进度变化 时触发 （触发频率 250ms 一次）
        videoUpdate(event) {
            //进度条 绑定视频播放进度
            let duration = this.videoTime;
            let sliderValue = (event.detail.currentTime / duration) * 100;
            let second = (sliderValue / 100) * duration;
            this.sliderValue = second;
            //视频总时长
            this.druationTime = this.formatSeconds(duration);
            //视频当前播放时长
            this.currtime = this.formatSeconds(second);
        },
        //播放完 时触发 （跳转到视频开始，这里要禁止循环播放）
        videoEnded(event) {
            this.videoIsPaly = true; //显示暂停图标
            this.isShowIcon = true; //不一秒后隐藏图标
            this.sliderValue = 0; //进度条跳到最开始位置
            // this.videoContext.seek(0);  //视频跳到最开始位置
        },
        //时间格式  秒 -》时:分:秒
        formatSeconds(a) {
            let hh = parseInt(a / 3600);
            let mm = parseInt((a - hh * 3600) / 60);
            if (mm < 10) mm = "0" + mm;
            let ss = parseInt((a - hh * 3600) % 60);
            if (ss < 10) ss = "0" + ss;
            if (hh < 10) hh = hh == 0 ? "" : `0${hh}:`;
            let length = hh + mm + ":" + ss;
            if (a >= 0) {
                return length;
            } else {
                return "00:00";
            }
        },

        // 触摸滑动
        touchMove(e) {
            // 如果评论面板打开，禁止滑动
            if (this.commontShow) {
                return;
            }
            // 如果高度未正确初始化，禁止滑动
            if (!this.videoRealHeight || this.videoRealHeight <= 0) {
                return;
            }
            this.transition = "none"; // 滑动时禁用过渡效果，保证跟手
            this.moveY = e.touches[0].pageY;
            
            // 计算当前视频的正确位置（负值）
            let currentVideoTop = -this.currentIndex * this.videoRealHeight;
            // 滑动偏移量
            let moveOffset = this.moveY - this.startY;
            
            if (this.moveY > this.startY) {
                // 向下滑动（返回上一个视频）
                this.moveDirection = "up";
                if (this.currentIndex == 0) {
                    // 第一个视频，限制下拉范围
                    this.marginTop = moveOffset > 50 ? 50 : moveOffset;
                } else {
                    this.marginTop = currentVideoTop + moveOffset;
                }
            } else {
                // 向上滑动（查看下一个视频）
                this.moveDirection = "down";
                if (this.videoList.length == 0) {
                    return;
                }
                if (this.currentIndex == this.videoList.length - 1) {
                    // 最后一个视频，限制上拉范围
                    let minTop = currentVideoTop - 50;
                    let newTop = currentVideoTop + moveOffset;
                    this.marginTop = newTop < minTop ? minTop : newTop;
                } else {
                    this.marginTop = currentVideoTop + moveOffset;
                }
            }
        },
        // 触摸结束
        touchEnd(e) {
            this.transition = "all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94)"; // 更流畅的缓动效果
            // 如果高度未正确初始化，重置状态并返回
            if (!this.videoRealHeight || this.videoRealHeight <= 0) {
                this.marginTop = -this.currentIndex * this.videoRealHeight;
                this.fixMarginTop = this.marginTop;
                this.startY = 0;
                this.moveY = 0;
                return;
            }
            
            // 第一个视频下拉刷新
            if (this.currentIndex == 0 && this.marginTop >= 45) {
                this.$emit("refresh");
                this.marginTop = 0;
                this.fixMarginTop = 0;
                this.startY = 0;
                this.moveY = 0;
                return;
            }
            
            // 最后一个视频上拉加载更多
            if (
                this.currentIndex == this.videoList.length - 1 &&
                this.marginTop < -this.currentIndex * this.videoRealHeight - 45
            ) {
                this.marginTop = -this.currentIndex * this.videoRealHeight;
                this.fixMarginTop = this.marginTop;
                this.$emit("loadMore");
                this.startY = 0;
                this.moveY = 0;
                return;
            }
            
            let millisecond = new Date().getTime() - this.startTime;
            let moveDistance = Math.abs(this.moveY - this.startY);
            
            // 优化滑动阈值：快速滑动50px或慢速滑动超过屏幕1/5
            let shouldSwitch = 
                (moveDistance > 50 && millisecond < 300) || 
                (moveDistance > this.videoRealHeight / 5);
            
            if (shouldSwitch) {
                if (this.moveDirection == "up") {
                    // 向下滑动，返回上一个视频
                    if (this.currentIndex > 0) {
                        this.currentIndex = this.currentIndex - 1;
                        this.$emit("update:videoIndex", this.currentIndex);
                        this.currentComment = this.videoList[this.currentIndex].commentObj;
                        this.videoPlayChange();
                    }
                } else {
                    // 向上滑动，查看下一个视频
                    if (this.currentIndex < this.videoList.length - 1) {
                        this.currentIndex = this.currentIndex + 1;
                        this.$emit("update:videoIndex", this.currentIndex);
                        this.currentComment = this.videoList[this.currentIndex].commentObj;
                        this.videoPlayChange();
                    }
                }
            } else {
                console.log('滑动距离不够，回弹到当前视频');
            }
            
            // 始终基于currentIndex计算marginTop，使用Math.round避免浮点数误差
            const targetPosition = -this.currentIndex * this.videoRealHeight;
            this.marginTop = Math.round(targetPosition);
            this.fixMarginTop = this.marginTop;
            
            console.log(`[touchEnd] =====================================`);
            console.log(`[touchEnd] currentIndex: ${this.currentIndex}`);
            console.log(`[touchEnd] videoRealHeight: ${this.videoRealHeight}px`);
            console.log(`[touchEnd] 计算公式: -${this.currentIndex} × ${this.videoRealHeight} = ${targetPosition}`);
            console.log(`[touchEnd] 最终marginTop: ${this.marginTop}px`);
            console.log(`[touchEnd] =====================================`);
            
            // 强制触发重绘确保位置生效
            this.$forceUpdate();
            
            this.startY = 0;
            this.moveY = 0;
        },
        // 滑动切换
        videoPlayChange() {
            // 立即停止其他视频
            this.stopOtherVideo();
            
            // 等待DOM更新后再播放新视频，确保旧视频已销毁
            this.$nextTick(() => {
                if (
                    this.videoList[this.currentIndex].recordType === "0" ||
                    this.videoList[this.currentIndex].recordType === "8"
                ) {
                    // 再等待一帧，确保新视频元素已渲染
                    setTimeout(() => {
                        let video = uni.createVideoContext(
                            this.videoList[this.currentIndex].id,
                            this
                        );
                        this.currentVideo = video;
                        // 先seek到开始位置
                        this.currentVideo.seek(0);
                        // 再等待一帧后播放
                        this.$nextTick(() => {
                            if (this.currentVideo) {
                                this.currentVideo.play();
                                this.currentStatus = "play";
                            }
                        });
                        currentAudio.pause();
                    }, 150); // 稍微延迟确保新视频元素已就绪
                } else {
                    this.currentStatus = "play";
                    currentAudio.seek(0);
                    currentAudio.play();
                }
            });
            // 分享 数据
            this.$emit("share", this.videoList[this.currentIndex]);
        },
        // 暂停其他视频
        stopOtherVideo() {
            this.videoList.map((v) => {
                let video = uni.createVideoContext(v.id, this);
                video.seek(0);
                video.pause();
                if (currentAudio) {
                    currentAudio.pause();
                    currentAudio.seek(0);
                }
            });
        },
        // 暂停/播放视频/双击点赞事件
        pauseVideo(e, item) {
            console.log(item, "item");
            // 视频对象为空,返回
            if (
                ((item.recordType === "0" || item.recordType === "8") &&
                    !this.currentVideo) ||
                (item.recordType === "1" && !currentAudio)
            )
                return;
            if (this.commontShow) {
                this.commontShow = false;
                return;
            }
            clearTimeout(this.clickTimer);
            let currentTime = new Date().getTime();
            let timeRange = currentTime - this.clickTime;
            if (timeRange < 300) {
                // 双击事件
                // if (item.isFabulous != 0) {
                this.$emit("fabulous", item, true);
                // }
                this.dbClickAnimation(e);
            } else {
                // 单击事件
                this.clickTimer = setTimeout(() => {
                    e.preventDefault();
                    e.stopPropagation();
                    if (this.currentStatus == "play") {
                        this.currentStatus = "pause";
                        if (item.recordType === "1") {
                            currentAudio.pause();
                            return;
                        }
                        this.currentVideo.pause();
                    } else {
                        this.currentStatus = "play";
                        if (item.recordType === "1") {
                            currentAudio.play();
                            return;
                        }
                        this.currentVideo.play();
                    }
                }, 300);
            }
            this.clickTime = new Date().getTime();
        },
        // 已有爱心叠加双击事件
        fabulousDbClick(e) {
            clearTimeout(this.fabulousTimer);
            let currentTime = new Date().getTime();
            let timeRange = currentTime - this.fabulousTime;
            if (timeRange < 300) {
                // 双击事件
                this.dbClickAnimation(e);
            } else {
            }
            this.fabulousTime = new Date().getTime();
        },
        // 双击点赞动画
        dbClickAnimation(e) {
            let deg = Math.round(Math.random() * 40 + 5);
            this.fabulousArr.push({
                left: e.detail.x - 25 + "px",
                top: e.detail.y - 25 + "px",
                transform: "rotate(" + (deg % 2 == 0 ? deg : -deg) + "deg)",
                createTime: new Date().getTime(),
            });

            let index =
                this.fabulousArr.length > 0 ? this.fabulousArr.length - 1 : 0;
            setTimeout(() => {
                this.$set(
                    this.fabulousArr,
                    index,
                    Object.assign(this.fabulousArr[index], {
                        opacity: 0,
                        transform:
                            "scale(3) " + this.fabulousArr[index].transform,
                    })
                );
                setTimeout(() => {
                    this.fabulousArr.splice(index, 1, null);
                }, 1000);
            }, 500);

            if (this.videoList[this.currentIndex].isFabulous != 1) {
                this.$set(
                    this.videoList,
                    this.currentIndex,
                    Object.assign(this.videoList[this.currentIndex], {
                        isFabulous: 1,
                        fabulousCount:
                            this.videoList[this.currentIndex].fabulousCount + 1,
                    })
                );
            }
        },
        // 定时清除点赞动画元素
        clearFabulousArr() {
            const indexArr = this.fabulousArr.map((v, i) => {
                if (v.opacity == "0") {
                    return i;
                }
            });
            indexArr.forEach((v) => {
                this.fabulousArr.splice(v, 1);
            });
        },
        // 点赞切换
        toggleFabulous(item, index) {
            this.$emit("fabulous", item, item.isFabulous == 1 ? false : true);
            this.$set(
                this.videoList,
                index,
                Object.assign(item, {
                    isFabulous: item.isFabulous == 1 ? 0 : 1,
                    fabulousCount:
                        item.isFabulous == 1
                            ? item.fabulousCount - 1
                            : item.fabulousCount + 1,
                })
            );
        },
        // 评论
        // commontAdd() {
        //     uni.showToast({
        //         title: "该功能暂未开放",
        //         icon: "none",
        //     });
        //     return;
        //     this.commontShow = true;
        //     this.replyType = "video";
        //     this.replyObj = this.currentVideo;
        // },
        // 分享
        shareFunc(item) {
            this.$emit("share", item);
        },
        // 购物车
        goToGoodsFunc(item) {
            this.$emit("goToGoodsFunc", item);
        },
        // 标签
        goToBiaoQian(v) {
            this.$emit("goToBiaoQian", v);
        },
        // 关注
        followFunc(index, item) {
            let flag = item.isFollow == 1 ? false : true;
            if (flag) {
                uni.showToast({
                    title: "关注成功",
                    icon: "none",
                });
            } else {
                uni.showToast({
                    title: "取消关注",
                    icon: "none",
                });
            }
            this.$emit("follow", item, flag);
            this.$set(
                this.videoList,
                index,
                Object.assign(item, {
                    isFollow: item.isFollow == 1 ? 0 : 1,
                })
            );
        },
        // 评论点赞
        commentFabulous(level, item, index, childIndex) {
            const result = item.isFabulous == "1" ? "0" : "1";
            item.isFabulous = result;
            if (result == "1") {
                item.fabulousCount = item.fabulousCount + 1;
            } else {
                item.fabulousCount = item.fabulousCount - 1;
            }
            if (level === "first") {
                this.currentComment.list[index] = item;
            } else {
                this.currentComment.list[index].children[childIndex] = item;
            }
            this.$emit("commentFabulous", item);
        },
        // 回复评论
        reply(level, item, index, childIndex) {
            this.showInput = true;
            this.commentPlaceholder = `回复@${item.userNick}`;
            this.replyIndex = childIndex;
            this.replyType = level;
            this.replyParentIndex = index;
            this.replyObj = item;
        },
        // 提交评论
        commentCommit() {
            this.showInput = false;
            if (this.replyType == "video") {
                this.currentComment.list.push({
                    userHead:
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F5e%2F4e%2Ff0%2F5e4ef0e451852e0114d75eac14f60924.jpeg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642669624&t=028d851350e18512dbf4bfe3a86cbfa4",
                    userNick: "yjyyyyy",
                    content: this.replyContent,
                    fabulousCount: 0,
                });
            } else if (this.replyType == "first") {
                this.currentComment.list[this.replyParentIndex].children.push({
                    userHead:
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F5e%2F4e%2Ff0%2F5e4ef0e451852e0114d75eac14f60924.jpeg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642669624&t=028d851350e18512dbf4bfe3a86cbfa4",
                    userNick: "yjyyyyy",
                    content: this.replyContent,
                    fabulousCount: 0,
                    replyTo: this.replyObj.userNick,
                });
            } else {
                this.currentComment.list[this.replyParentIndex].children.push({
                    userHead:
                        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fedpic%2F5e%2F4e%2Ff0%2F5e4ef0e451852e0114d75eac14f60924.jpeg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1642669624&t=028d851350e18512dbf4bfe3a86cbfa4",
                    userNick: "yjyyyyy",
                    content: this.replyContent,
                    fabulousCount: 0,
                    replyTo: this.replyObj.userNick,
                });
            }
            this.replyContent = "";
        },
        // 收起键盘
        commentBlur() {
            this.commentPlaceholder = `说点好听的～`;
            this.showInput = false;
            this.replyType = "video";
            this.replyObj = this.currentVideo;
        },
        // 下载视频
        saveVideo(item) {
            // 打开loading等待
            uni.showLoading({ mask: true, title: "加载中" });
            // 先下载视频
            uni.downloadFile({
                url: item.videoUrl || item.videoCover,
                success: (res) => {
                    const that = this;
                    if (res.statusCode === 200) {
                        // 关闭loading
                        uni.hideLoading();
                        // 保存视频到手机相册
                        uni.saveVideoToPhotosAlbum({
                            filePath: res.tempFilePath,
                            success: function () {
                                uni.showToast({
                                    title: "保存成功",
                                    icon: "none",
                                });
                            },
                        });
                    }
                },
            });
        },
        downSaveImage(item) {
            const that = this;
            // 获取用户是否开启 授权保存图片到相册。
            uni.getSetting({
                success(res) {
                    // 如果没有授权
                    if (!res.authSetting["scope.writePhotosAlbum"]) {
                        // 则拉起授权窗口
                        uni.authorize({
                            scope: "scope.writePhotosAlbum",
                            success() {
                                //点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
                                that.saveVideo(item);
                            },
                            fail(error) {
                                //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
                                uni.showModal({
                                    title: "提示",
                                    content: "若点击不授权，将无法保存视频",
                                    cancelText: "不授权",
                                    cancelColor: "#999",
                                    confirmText: "授权",
                                    confirmColor: "#f94218",
                                    success(res) {
                                        if (res.confirm) {
                                            // 选择弹框内授权
                                            uni.openSetting({
                                                success(res) {},
                                            });
                                        } else if (res.cancel) {
                                            // 选择弹框内 不授权
                                        }
                                    },
                                });
                            },
                        });
                    } else {
                        // 有权限--直接保存
                        that.saveVideo(item);
                    }
                },
                fail: (error) => {
                    uni.showToast({
                        title: error.errMsg,
                        icon: "none",
                        duration: 1500,
                    });
                },
            });
        },
    },
};
</script>

<style lang="scss" scoped>
@import "@/static/css/font.css";

.slider-container {
    width: 100%;
    .isSlider {
        width: 70%;
        margin: 0 auto 20rpx;
    }
}

.color-red {
    color: #f73b3b;
}

.inline-block {
    display: inline-block;
    vertical-align: middle;
}

// 喜欢按钮动画
.iconxihuan,
.icon-follow {
    transition: all 0.3s;
}

.iconxihuan:active,
.icon-follow:active {
    transform: scale(1.5);
}

@keyframes double-fabulous {
    from {
        opacity: 1;
        transform: scale(1);
    }

    to {
        opacity: 0;
        transform: scale(3);
    }
}

// 双击点赞样式
.fabulous-item {
    position: absolute;
    z-index: 99999;
    width: 86rpx;
    height: 86rpx;
    color: #f73b3b;
    font-size: 100rpx;
    // animation: double-fabulous 5s;
    transform-origin: 50% 100%;
    transition: opacity 0.8s, transform 0.8s;
    opacity: 0.8;
}

// 评论框
.commont-box {
    position: fixed;
    z-index: -1;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 60%;
    overflow-y: auto;
    background-color: #222;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    transition: all 0.3s;
    transform: translateY(100%);
    display: flex;
    flex-direction: column;

    &.active {
        z-index: 9;
        transform: translateY(0);
    }

    .commont-title {
        text-align: center;
        color: white;
        font-size: 24rpx;
        margin: 20rpx 0;
        font-weight: bold;
    }

    .commont-list {
        flex: 1;
        overflow-y: auto;

        .comment-panel {
            margin: 30rpx 40rpx;
            display: flex;

            .first-user {
                width: 50rpx;
                height: 50rpx;
                border-radius: 100%;
            }

            .first-comment {
                flex: 1;
                margin: 0rpx 20rpx;

                .comment-name {
                    font-size: 24rpx;
                    font-weight: bold;
                    color: #999;
                }

                .comment-content {
                    color: white;
                    font-size: 26rpx;
                    margin-top: 10rpx;
                }

                .time-box {
                    margin-top: 10rpx;
                    font-size: 24rpx;
                    color: #999;

                    .reply-btn {
                        margin-left: 20rpx;
                    }
                }
            }

            .fabulous-box {
                text-align: center;
                color: #666;

                .fabulous-btn {
                    font-size: 36rpx;
                    transition: color 0.3s;
                }

                .fabulous-text {
                    font-size: 24rpx;
                    color: #999;
                }
            }
        }
    }

    .comment-input {
        display: block;
        margin: 10px auto;
        box-sizing: border-box;
        width: 90%;
        height: 70rpx;
        padding: 0 20px;
        border-radius: 60rpx;
        background-color: #4a4a4a;
        color: white;
    }
}

// 全局容器
.widget-video {
    width: 100vw;
    height: 100%;
    overflow: hidden;
    position: relative;

    .scroll-video-box {
        min-height: 100%;
        position: relative;
        will-change: transform; // 提示浏览器优化transform动画
        transform: translateZ(0); // 开启硬件加速
        backface-visibility: hidden; // 优化3D变换性能

        .empty-txt {
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
        }
    }

    .refresh-box {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .load-more-box {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    // 视频容器
    .video-item-box {
        position: relative;
        transform: translateZ(0); // 开启硬件加速
        backface-visibility: hidden; // 优化渲染性能

        .btn-play {
            font-size: 80rpx;
            color: white;
            position: absolute;
            top: 50%;
            left: 50%;
            transition: all 0.3s;
            transform: translateX(-50%) translateY(-50%) scale(1.5);
            z-index: 8;
            opacity: 0;

            &.show {
                opacity: 0.5;
                transform: translateX(-50%) translateY(-50%) scale(1);
            }
        }

        .video-cover {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            background-color: #000;
            object-fit: cover; // 确保封面填充
        }

        .fullscreen-video {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
            background-color: #000; // 避免白屏
            transform: translateZ(0); // 硬件加速
        }

        .video-info {
            width: 100rpx;
            position: absolute;
            right: 20rpx;
            bottom: 100rpx;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            .atavar-box {
                background-color: white;
                padding: 6rpx;
                box-sizing: border-box;
                border-radius: 100%;
                width: 86rpx;
                height: 86rpx;
                margin-bottom: 40rpx;
                position: relative;

                .atavar-img {
                    width: 100%;
                    height: 100%;
                    display: block;
                    border-radius: 100%;
                }

                .add-follow-btn {
                    width: 40rpx;
                    height: 40rpx;
                    padding: 4rpx;
                    border-radius: 100%;
                    color: white;
                    background-color: #f73b3b;
                    position: absolute;
                    bottom: -24rpx;
                    left: 50%;
                    transform: translateX(-50%);
                    font-weight: bold;
                    text-align: center;
                    line-height: 32rpx;

                    .iconjia1 {
                        font-size: 26rpx;
                    }
                }
            }

            .icon-box {
                width: 100rpx;
                height: 100rpx;
                margin-top: 30rpx;
                display: flex;
                align-items: center;
                justify-content: space-around;
                flex-direction: column;
                color: white;

                .icon-btn {
                    font-size: 60rpx;
                }

                .count-text {
                    font-size: 24rpx;
                }
            }
        }

        .video-title {
            position: absolute;
            left: 20rpx;
            bottom: 80rpx;
            width: calc(100% - 160rpx);
            color: white;
            z-index: 1;

            .user-name {
                font-weight: bold;
            }

            .video-content {
                font-size: 24rpx;
            }
        }
    }
}
</style>
